package com.spark.netty.demo1.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author lvhuiyuan
 * @date 2020-06-19 17:22
 * 服务端Handler
 */
//1@Sharable 标识这类的实例之间可以在 channel 里面共享
@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("服务端收到消息：" + in.toString(CharsetUtil.UTF_8));
        in = Unpooled.copiedBuffer(("你好," + in.toString(CharsetUtil.UTF_8)).getBytes(CharsetUtil.UTF_8));
        System.out.println("服务端发送回复: " + in.toString(CharsetUtil.UTF_8));        //2
        ctx.write(in);                            //3将所接收的消息返回给发送者。注意，这还没有冲刷数据
        new Thread(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("我又来了，".getBytes(CharsetUtil.UTF_8)));
        }).start();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4冲刷所有待审消息到远程节点。关闭通道后，操作完成
                .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();                //5
        ctx.close();                            //6关闭通道
    }
}
